<style>
/* 自定义对话框样式 */
.scroll-dialog .el-dialog__body {
  max-height: 70vh;
  overflow-y: auto;
}
</style>

<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px"
             style="padding-bottom: 30px"
    >
      <el-col :span="6" :offset="0.5">
        <el-form-item label="连接名称" prop="dbName">
          <el-input
            v-model="queryParams.dbName"
            placeholder="请输入连接名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="连接地址" prop="dbUrl">
          <el-input
            v-model="queryParams.dbUrl"
            placeholder="请输入连接地址"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
      </el-col>
      <el-form-item align="right">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button icon="el-icon-add" size="mini" @click="handleFormAdd">添加</el-button>
      </el-form-item>
    </el-form>


    <el-table v-loading="loading" :data="datasourceList" @selection-change="handleSelectionChange">
      <el-table-column width="200px" label="id" align="center" prop="id" fixed/>
      <el-table-column width="200px" label="连接名称" align="center" prop="dbName"/>
      <el-table-column width="200px" label="驱动类型" align="center" prop="driverClass"/>
      <el-table-column width="200px" label="验证语句" align="center" prop="dbCheckUrl"/>
      <el-table-column width="200px" label="初始连接数" align="center" prop="initialSize"/>
      <el-table-column width="200px" label="最大连接数" align="center" prop="maxActive"/>
      <el-table-column width="200px" label="最大空闲数" align="center" prop="maxIdle"/>
      <el-table-column width="200px" label="最大等待时间" align="center" prop="maxWait"/>
      <el-table-column width="200px" label="状态" align="center" prop="dbState"/>
      <el-table-column width="200px" label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['websql:datasource:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog :close-on-click-modal="false"
               :close-on-press-escape="false"
               :lock-scroll="false"
               custom-class="scroll-dialog" :title="addForm.title" :visible.sync="addForm.open" width="800px"
               append-to-body>
      <el-form ref="form" :model="addForm.form" :rules="rules" label-width="150px">
        <el-form-item label="数据库类型" prop="echoData">
          <div style="display: flex; align-items: center; gap: 8px; width: 100%">
            <el-select
              v-model="echoData"
              placeholder="请选择数据库类型"
              clearable
              filterable
              @change="echoDriverConfig"
              style="flex: 1"
            >
            <el-option
              v-for="dbDriverConfig in dbDiverConfigList"
              :key="dbDriverConfig.id"
              :label="dbDriverConfig.name"
              :value="dbDriverConfig.id"
            />
            </el-select>
            <el-button type="primary" @click="testDatasource">测 试</el-button>
          </div>
        </el-form-item>
        <el-form-item label="连接名称" prop="dbName">
          <el-input v-model="addForm.form.dbName" placeholder="请输入连接名称"/>
        </el-form-item>
        <el-form-item label="驱动名称" prop="driverClass">
          <el-input v-model="addForm.form.driverClass" placeholder="请输入驱动名称"/>
        </el-form-item>
        <el-form-item label="连接地址" prop="dbUrl">
          <el-input type="textarea"
                    :autosize="{ minRows: 4, maxRows: 8}" v-model="addForm.form.dbUrl" placeholder="请输入连接地址"/>
        </el-form-item>
        <el-form-item label="验证语句" prop="dbCheckUrl">
          <el-input v-model="addForm.form.dbCheckUrl" placeholder="请输入验证语句"/>
        </el-form-item>
        <el-form-item label="登录账号" prop="dbAccount">
          <el-input v-model="addForm.form.dbAccount"
                    placeholder="请输入登录账号"/>
        </el-form-item>
        <el-form-item label="登录密码" prop="dbPassword">
          <el-input v-model="addForm.form.dbPassword" placeholder="登录密码"/>
        </el-form-item>
        <el-form-item label="初始大小" prop="initialSize">
          <el-input v-model="addForm.form.initialSize" placeholder="请输入初始大小"/>
        </el-form-item>
        <el-form-item label="最大连接数" prop="maxActive">
          <el-input v-model="addForm.form.maxActive" placeholder="请输入最大连接数"/>
        </el-form-item>
        <el-form-item label="最大空闲数" prop="maxIdle">
          <el-input v-model="addForm.form.maxIdle" placeholder="请输入最大空闲数"/>
        </el-form-item>
        <el-form-item label="最大等待时间(ms)" prop="maxWait">
          <el-input v-model="addForm.form.maxWait" placeholder="请输入最大等待时间(ms)"/>
        </el-form-item>
        <el-form-item label="状态" prop="dbState">
          <el-select v-model="addForm.form.dbState"
                     placeholder="请选择状态"
                     clearable
                     filterable
          >
            <el-option
              v-for="dbState in dbStateList"
              :key="dbState.value"
              :label="dbState.value"
              :value="dbState.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveDatasource">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listDatasource,
  getDatasource,
  delDatasource,
  addDatasource,
  updateDatasource,
  testDatasource, checkConnectName
} from "@/api/websql/datasource";
import {getById, getDriverConfigList} from "@/api/websql/driverConfig";
import {findTableFieldByDatabase, metaTreeTableList} from "@/api/websql/sqlManager";
import data from "@/views/system/dict/data";

export default {
  name: "Datasource",
  data() {
    return {
      echoData: {
        id: 1,
        name: "mysql",
        driverClass: null,
        url: null,
        dbCheckUrl: null
      },
      dbStateList: [
        {id: 1, value: "有效"},
        {id: 2, value: "无效"},
      ],
      dbDiverConfigList: null,
      addForm: {
        open: false,
        title: null,
        form: {},
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // ***表格数据
      datasourceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        dbAccount: null,
        dbCheckUrl: null,
        dbName: null,
        dbPassword: null,
        dbState: null,
        dbUrl: null,
        driverClass: null,
        ID: null,
        initialSize: null,
        maxActive: null,
        maxIdle: null,
        maxWait: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {}
    };
  },
  created() {
    this.getDriverConfigList();
    this.getList();
    // 测试数据源拉取
    // findTableFieldByDatabase("websql-dm").then(res=>{
    //   console.log(`findTableFieldByDatabase>> ${JSON.stringify(res.data)}`)
    // })

    // metaTreeTableList().then(res=>{
    //   console.log(`metaTreeTableList>> ${JSON.stringify(res.data)}`)
    // })
  },
  methods: {
    async testDatasource() {
      const res = await checkConnectName(this.addForm.form.dbName);
      if (res.data) {
        await testDatasource(this.addForm.form).then(res => {
          this.$notify({
            title: `数据源连接测试`,
            message: res.data,
            type: 'warning',
            duration: 5000,
          });
        })
        // alert(JSON.stringify(this.addForm.form));
      } else {
        this.$notify({
          title: `数据源连接测试`,
          message: '数据源名称重复',
          type: 'warning',
          duration: 5000,
        });
      }
      return res.data;
    },
    async saveDatasource() {
      const res = await this.testDatasource();
      if (res) {
        await addDatasource(this.addForm.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.addForm.open = false;
          this.getList();
        });
      } else {
        this.$modal.msgError("新增失败");
      }
    },
    echoDriverConfig() {
      getById(this.echoData).then(res => {
        this.addForm.form.dbName = `websql-${res.data[0].name}`;
        this.addForm.form.driverClass = res.data[0].driverClass;
        this.addForm.form.dbUrl = res.data[0].url;
        this.addForm.form.dbCheckUrl = res.data[0].dbCheckUrl;
      })

      // this.addForm.form.dbName=`websql-${this.echoData.name}`;
      // this.addForm.form.driverClass=this.echoData.driverClass;
      // this.addForm.form.dbUrl=this.echoData.url;
      // this.addForm.form.dbCheckUrl=this.echoData.dbCheckUrl;
    },
    getDriverConfigList() {
      getDriverConfigList().then(res => {
        this.dbDiverConfigList = res.data;
        // console.log(`##dbDiverConfigList：${JSON.stringify(this.dbDiverConfigList)}`);
      })
    },
    // TODO 取消后数据清空
    handleFormAdd() {
      this.echoData = null;
      this.addForm.form = {
        dbAccount: null,
        dbCheckUrl: null,
        dbName: null,
        dbPassword: null,
        dbState: "有效",
        dbUrl: null,
        driverClass: null,
        ID: null,
        initialSize: 5,
        maxActive: 20,
        maxIdle: 5,
        maxWait: 2000
      };
      this.addForm.title = "添加数据源";
      this.addForm.open = true;
    },
    /** 查询***列表 */
    getList() {
      this.loading = true;
      listDatasource(this.queryParams).then(response => {
        this.datasourceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.addForm.open = false;
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        dbAccount: null,
        dbCheckUrl: null,
        dbName: null,
        dbPassword: null,
        dbState: null,
        dbUrl: null,
        driverClass: null,
        ID: null,
        initialSize: null,
        maxActive: null,
        maxIdle: null,
        maxWait: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.dbAccount)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加***";
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const dbAccounts = row.id || this.ids;
      this.$modal.confirm('是否确认删除编号为"' + dbAccounts + '"的数据项？').then(function () {
        return delDatasource(dbAccounts);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('websql/datasource/export', {
        ...this.queryParams
      }, `datasource_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
